<template>
  <div>
    <h3>计费管理 / 缴费类型管理</h3>
    <div class="box">
      <div class="left">
        <el-input
          v-model="input"
          placeholder="项目价格"
          style="width: 250px"
        ></el-input>
        <el-select
          v-model="value"
          clearable
          placeholder="通知状态"
          style="margin-left: 10px"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-tree
          :data="data"
          :props="defaultProps"
          @node-click="handleNodeClick"
          style="margin-top: 20px"
        ></el-tree>
      </div>
      <div class="right">
        <div class="first">
          <h2>{{title}}</h2>
          <div class="anniu">
            <el-button type="primary" icon="el-icon-search" @click="fetchData">查询</el-button>
            <el-button type="success" icon="el-icon-plus" @click="add">新增</el-button>
            <el-button type="primary" icon="el-icon-refresh-left" @click="refreshData"
              >刷新</el-button
            >
            <el-button type="primary" icon="el-icon-upload2" @click="exportExcel">导出</el-button>
          </div>
        </div>
        <el-table
          :data="tableData"
          style="width: 100%"
          :default-sort="{ prop: 'paytime', order: 'descending' }"
          v-loading="loading"
        >
          <el-table-column prop="payname" label="缴费项目名称" width="100" align="center">
          </el-table-column>
          <el-table-column prop="paylevel" label="缴费项目优先级" width="110" align="center">
          </el-table-column>
          <el-table-column prop="paynum" label="项目用量/时长" align="center" width="100">
          </el-table-column>
          <el-table-column prop="paymoney" label="项目价格" sortable width="100" align="center">
          </el-table-column>
          <el-table-column prop="paytime" label="创建时间" sortable width="110" align="center">
            <template slot-scope="scope">
              {{ formatTime(scope.row.paytime) }}
            </template>
          </el-table-column>
          <el-table-column prop="username" label="通知人" width="100" align="center">
            <template slot-scope="scope">
              {{ scope.row.username === null? "暂无": scope.row.username }}
            </template>
          </el-table-column>
          <el-table-column prop="paystatus" label="状态" width="100" align="center">
            <template slot-scope="scope">
              {{ scope.row.paystatus === 1 ? '已通知' : '未通知' }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
               <template slot-scope="scope"> 
              <el-button size="mini" icon="el-icon-edit"  @click="notice(scope.row)">通知</el-button>
              <el-button size="mini" icon="el-icon-delete" @click="look(scope.row)">查看</el-button>
              <el-button size="mini" icon="el-icon-delete"  @click="delete1(scope.row)">作废</el-button>
               </template>
          </el-table-column>
        </el-table>
        <div class="pagination" style="margin-top: 15px; text-align: right;">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="current"
            :page-sizes="[1, 2, 5,10]"
            :page-size="page"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </div>
    </div>
    <el-dialog title="计费管理" :visible.sync="dialogTableVisible"> 
      <el-input v-model="input" placeholder="请输入内容" style="width:400px;"></el-input>
      <el-button type="primary" icon="el-icon-search" style="margin-left:10px;" @click="chazhao"></el-button>
      <el-button type="warning" icon="el-icon-refresh-left" @click="chongzhi">重置</el-button>
  <el-table :data="tableData1" highlight-current-row @row-click="handleUserRowClick">
    <el-table-column property="date" label="序号">
      <template slot-scope="scope">
              {{ scope.$index+1 }}
            </template>
    </el-table-column>
    <el-table-column property="username" label="用户账号"></el-table-column>
    <el-table-column property="homeaddress" label="家庭住址" width="200"></el-table-column>
    <el-table-column property="type" label="类型">
      <template slot-scope="scope">
              {{ scope.row.type === "1"? "管理员" : "普通用户"}}
            </template>
    </el-table-column>
    <el-table-column property="" label="缴费状态">{{this.coststatus === "1"? "已缴费" :" 未交费"}}</el-table-column>
  </el-table>
  <div class="block">
    
    <el-pagination
      @size-change="handleSizeChange1"
      @current-change="handleCurrentChange1"
      :current-page="current1"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="page1"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total1">
    </el-pagination>
  </div>
  <div class="zhezhao">
  <div class="last">
    <el-button type="primary" @click="close">取消</el-button>
    <el-button type="primary" @click="tongzhi">通知</el-button>
  </div>
  </div>
</el-dialog>
  </div>
  
</template>
<script>
import * as XLSX from 'xlsx';
export default {
  data() {
    return {
      id:"",
      ids:"",
      input:"",
      tableData:[],
      dialogTableVisible: false,
      formLabelWidth: '120px',
      title: "",
      
      value: "",
      loading: false,
      options: [
        {
          value: "1",
          label: "已通知",
        },
        {
          value: "2",
          label: "未通知",
        },
      ],
      // 树形数据添加id标识，用于接口查询
      data: [
        {
          label: "缴费项目",
          children: [
            {
              label: "电费项目",
              children: [
                {
                  label: "电费目录表",
                  id: "7"  // 对应后端c_id=7
                },
              ],
            },
            {
              label: "水费项目",
              children: [
                {
                  label: "水费固定月目录表",
                  id: "8"  // 假设对应c_id=8
                },
                {
                  label: "水费按量计价目录表",
                  id: "9"  // 假设对应c_id=9
                },
              ],
            },
            {
              label: "天然气项目",
              children: [
                {
                  label: "天然气目录表",
                  id: "10"  // 假设对应c_id=10
                },
              ],
            },
            {
              label: "物业费项目",
              children: [
                {
                  label: "物业费目录表",
                  id: "11"  // 假设对应c_id=11
                },
              ],
            },
            {
              label: "宽带费项目",
              children: [
                {
                  label: "宽带费目录表",
                  id: "12"  // 假设对应c_id=12
                },
              ],
            },
          ],
        },
      ],
      defaultProps: {
        children: "children",
        label: "label",
      },
      tableData1: [],
      current: 1,
      page: 10,
      total: 0,
      currentCid: "7" , // 当前选中的分类ID，默认电费
      current1:1,
      page1:10,
      total1:0,
      coststatus:"",
      username:"",
      
    };
  },
  methods: {
   async getlist(){
      let res = await this.$axios.get(`http://community.byesame.com/users/getUserList?username=${this.input}&currPage=${this.current1-1}&pageNum=${this.page1}`)
      console.log(res);
      this.tableData1 = res.data.data
      this.total1 = res.data.total
      
    },
   
    close(){
      this.dialogTableVisible = false
    },
   handleUserRowClick(selectedRow){

      this.username = selectedRow.username
   },
    tongzhi(){
    this.$confirm('确定通知改用户缴费?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
           let res = await this.$axios.post("http://community.byesame.com/cost/updateCostData",{
      u_id:Number(this.currentCid),
      c_id:this.id,
      coststatus:this.coststatus,
      paystatus:1,
      username:this.username,
      token:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsImVtYWlsIjoiMjQ1MzMxNzM1N0BxcS5jb20iLCJoZWFkIjoiMjAyNTEwMjcxNTE4NDA4MzUxMTQxLmpwZyIsInR5cGUiOiIxIiwiaWF0IjoxNzYxNjk4ODM2LCJleHAiOjE3NjE3ODUyMzZ9.q51a5NZjbxdj0WIbZUOYAaqBM1JqcyuzmpwzsoLIAeo"
     })
      console.log(res);
      this.dialogTableVisible = false
      this.fetchData();
          this.$message({
            type: 'success',
            message: '通知成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消通知'
          });          
        });
    
      },
    notice(row){
      this.id = row.id
      this.coststatus = row.coststatus
      this.username = row.username
      this.dialogTableVisible = true
      
      
    },
   
   async chazhao(){
      this.getlist();

    },
    async chongzhi(){
      this.input = ""
      this.getlist();
    },
    // 树形节点点击事件
    handleNodeClick(data) {
      if (data.id) {  // 只有带id的叶子节点才加载数据
        this.title = data.label;
        this.currentCid = data.id;
        this.current = 1;  // 重置页码
        this.fetchData();  // 加载对应数据
      } else {
        this.title = "";
        this.tableData = [];
      }
    },
    // 时间转换方法 - 将UTC时间转为本地时间
    formatTime(timeStr) {
      if (!timeStr) return "";
      const date = new Date(timeStr);
      // 补零函数
      const pad = (num) => num.toString().padStart(2, "0");
      return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} `;
    },
    // 获取数据
    async fetchData() {
      this.loading = true;
      try {
        const res = await this.$axios.get(`http://community.byesame.com/cost/getCostData`, {
          params: {
            c_id: this.currentCid,
            paymoney: this.input,  // 项目价格筛选
            paystatus: this.value,  // 通知状态筛选
            currPage: this.current - 1,
            pageNum: this.page
          }
        });
        this.tableData = res.data.data;
        this.total = res.data.total;
        this.ids = res.data.data.id
      } catch (error) {
        console.error("获取数据失败:", error);
        this.$message.error("获取数据失败，请重试");
      } finally {
        this.loading = false;
      }
    },
    // 刷新数据
    refreshData() {
      this.fetchData();
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.page = val;
      this.current = 1;
      this.fetchData();
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.current = val;
      this.fetchData();
    },
    handleSizeChange1(val) {
      this.page1 = val;
      this.current1 = 1;
      this.getlist();
    },
    // 当前页改变
    handleCurrentChange1(val) {
      this.current1 = val;
      this.getlist();
    },
    add(){
      
      
        this.$router.replace("addtype")
    },
    look(row){
      localStorage.setItem("payname",row.payname)
      localStorage.setItem("paylevel",row.paylevel)
      localStorage.setItem("paynum",row.paynum)
      localStorage.setItem("paymoney",row.paymoney)
      localStorage.setItem("username",row.username)
      localStorage.setItem("paystatus",row.paystatus)
      localStorage.setItem("paycontent",row.paycontent)
      this.$router.replace("looktype")
    },
    delete1(row){
    this.$confirm('确定永久作废这条计费项目?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          let res = await this.$axios.get(`http://community.byesame.com/cost/delCostData?id=${row.id}&token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsImVtYWlsIjoiMjQ1MzMxNzM1N0BxcS5jb20iLCJoZWFkIjoiMjAyNTEwMjcxNTE4NDA4MzUxMTQxLmpwZyIsInR5cGUiOiIxIiwiaWF0IjoxNzYxNjk4ODM2LCJleHAiOjE3NjE3ODUyMzZ9.q51a5NZjbxdj0WIbZUOYAaqBM1JqcyuzmpwzsoLIAeo`)
      console.log(res);
      this.fetchData();
          this.$message({
            type: 'success',
            message: '作废计费项目成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消作废该条计费项目'
          });          
        });
      
      
    },
    
     exportExcel() {
    // 1. 处理表格数据（可选：筛选需要导出的字段，避免导出多余数据）
    const exportData = this.tableData.map(item => ({
      "缴费项目名称": item.payname || "",  // 字段名对应Excel表头，值取自表格数据
      "缴费项目优先级": item.paylevel || "",
      "项目用量/时长": item.paynum || "",
      "项目价格": item.paymoney || "",
      "创建时间": this.formatTime(item.paytime) || "",  // 复用已有时间格式化方法
      "通知人": item.username || "暂无",
      "状态": item.paystatus === 1 ? "已通知" : "未通知"  // 状态文字化，更易读
    }));

    // 2. 创建Excel工作簿和工作表
    const wb = XLSX.utils.book_new();  // 新建工作簿
    const ws = XLSX.utils.json_to_sheet(exportData);  // 将处理后的数据转为工作表

    // 3. 将工作表添加到工作簿，并重命名工作表（默认是Sheet1）
    XLSX.utils.book_append_sheet(wb, ws, this.title || "计费项目数据");  // 用当前选中的目录名做表名

    // 4. 触发浏览器下载Excel文件
    XLSX.writeFile(wb, `${this.title || "计费项目数据"}_${new Date().toLocaleDateString()}.xlsx`);
    // 文件名格式：“目录名_日期.xlsx”，例如“电费目录表_2024-10-30.xlsx”
  },
  },
  created() {
    // 初始加载电费目录表数据
    this.title = "电费目录表";
    this.fetchData();
    this.getlist();
  }
};
</script>
<style scoped>
.zhezhao{
  height: 50px;
}
.last{
  float: right;
  margin-top: 10px;
}
.box {
  width: 99%;
  margin-top: 20px;
  display: flex;
}
.left {
  width: 30%;
}
.right {
  width: 65%;
  margin-left: 20px;
}
.first {
  width: 100%;
  margin-bottom: 15px;
  overflow: hidden;  /* 解决浮动问题 */
}
.first h2 {
  float: left;
  margin: 0;
  font-size: 18px;
}
.anniu {
  float: right;
}
/* 按钮间距 */
.anniu el-button {
  margin-left: 5px;
}
.pagination {
  margin-top: 15px;
  text-align: right;
}
</style>